package com.edu.exam.entity.curriculum.questionbank;

import com.edu.exam.entity.curriculum.classification.QuestionType;
import com.edu.exam.enums.exam.QuestionStatus;
import com.edu.exam.enums.analysis.AnalysisType;
import com.edu.exam.enums.analysis.DifficultyRating;
import com.edu.exam.enums.analysis.ImprovementPriority;
import com.edu.exam.enums.analysis.RevisionUrgency;
import com.edu.exam.enums.analysis.PerformanceTrend;
import com.edu.exam.enums.analysis.DataQuality;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 试题分析实体类
 * 所属模块：B-02 题库管理模块
 * 对应数据库表：question_analyses
 *
 * 管理试题的统计分析信息，包括难度评估、质量评价、使用统计等。
 * 支持多维度的试题分析和数据驱动的试题优化。
 */
@Entity
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class QuestionAnalysis {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull(message = "试题ID不能为空")
    @Column(name = "question_id", nullable = false)
    private Long questionId;

    @Column(name = "question_code", length = 50)
    private String questionCode;

    @Enumerated(EnumType.STRING)
    @Column(name = "question_type", length = 30)
    private QuestionType questionType;

    @Column(name = "paper_id")
    private Long paperId;

    @Column(name = "paper_code", length = 50)
    private String paperCode;

    @Column(name = "paper_name", length = 200)
    private String paperName;

    @NotNull(message = "分析类型不能为空")
    @Enumerated(EnumType.STRING)
    @Column(name = "analysis_type", nullable = false, length = 30)
    private AnalysisType analysisType;

    @NotNull(message = "分析日期不能为空")
    @CreationTimestamp
    @Column(name = "analysis_date", nullable = false)
    private LocalDateTime analysisDate;

    @Column(name = "analysis_period_start")
    private LocalDateTime analysisPeriodStart;

    @Column(name = "analysis_period_end")
    private LocalDateTime analysisPeriodEnd;

    // 基本统计指标
    @Column(name = "total_attempts")
    @Builder.Default
    private Long totalAttempts = 0L;

    @Column(name = "unique_users")
    @Builder.Default
    private Long uniqueUsers = 0L;

    @Column(name = "correct_attempts")
    @Builder.Default
    private Long correctAttempts = 0L;

    @Column(name = "incorrect_attempts")
    @Builder.Default
    private Long incorrectAttempts = 0L;

    @Column(name = "skipped_attempts")
    @Builder.Default
    private Long skippedAttempts = 0L;

    @Column(name = "not_answered")
    @Builder.Default
    private Long notAnswered = 0L;

    @Column(name = "partial_credit_attempts")
    @Builder.Default
    private Long partialCreditAttempts = 0L;

    // 准确率指标
    @Column(name = "accuracy_rate")
    private BigDecimal accuracyRate;

    @Column(name = "correct_rate")
    private BigDecimal correctRate;

    @Column(name = "incorrect_rate")
    private BigDecimal incorrectRate;

    @Column(name = "skip_rate")
    private BigDecimal skipRate;

    @Column(name = "non_response_rate")
    private BigDecimal nonResponseRate;

    // 分数统计
    @Column(name = "average_score")
    private BigDecimal averageScore;

    @Column(name = "max_score")
    private BigDecimal maxScore;

    @Column(name = "min_score")
    private BigDecimal minScore;

    @Column(name = "median_score")
    private BigDecimal medianScore;

    @Column(name = "mode_score")
    private BigDecimal modeScore;

    @Column(name = "standard_deviation")
    private BigDecimal standardDeviation;

    @Column(name = "variance")
    private BigDecimal variance;

    @Column(name = "score_range")
    private BigDecimal scoreRange;

    // 时间统计
    @Column(name = "average_time_spent")
    private Integer averageTimeSpent; // 秒

    @Column(name = "fastest_time")
    private Integer fastestTime; // 秒

    @Column(name = "slowest_time")
    private Integer slowestTime; // 秒

    @Column(name = "time_efficiency")
    private BigDecimal timeEfficiency;

    // 答案分布统计（选择题）
    @Column(name = "option_a_selected")
    @Builder.Default
    private Long optionASelected = 0L;

    @Column(name = "option_b_selected")
    @Builder.Default
    private Long optionBSelected = 0L;

    @Column(name = "option_c_selected")
    @Builder.Default
    private Long optionCSelected = 0L;

    @Column(name = "option_d_selected")
    @Builder.Default
    private Long optionDSelected = 0L;

    @Column(name = "option_e_selected")
    @Builder.Default
    private Long optionESelected = 0L;

    @Column(name = "option_f_selected")
    @Builder.Default
    private Long optionFSelected = 0L;

    @Column(name = "other_options_selected")
    @Builder.Default
    private Long otherOptionsSelected = 0L;

    @Column(name = "option_distribution")
    private String optionDistribution; // JSON格式的详细分布

    // 区分度分析
    @Column(name = "discrimination_index")
    private BigDecimal discriminationIndex;

    @Column(name = "point_biserial_correlation")
    private BigDecimal pointBiserialCorrelation;

    @Column(name = "biserial_correlation")
    private BigDecimal biserialCorrelation;

    @Column(name = "item_total_correlation")
    private BigDecimal itemTotalCorrelation;

    @Column(name = "difficulty_index")
    private BigDecimal difficultyIndex;

    // 难度分析
    @Enumerated(EnumType.STRING)
    @Column(name = "difficulty_rating", length = 20)
    private DifficultyRating difficultyRating;

    @Column(name = "observed_difficulty")
    private BigDecimal observedDifficulty;

    @Column(name = "expected_difficulty")
    private BigDecimal expectedDifficulty;

    @Column(name = "difficulty_mismatch")
    private Boolean difficultyMismatch;

    // 信度和效度指标
    @Column(name = "reliability_coefficient")
    private BigDecimal reliabilityCoefficient;

    @Column(name = "validity_measure")
    private BigDecimal validityMeasure;

    @Column(name = "content_validity")
    private BigDecimal contentValidity;

    @Column(name = "construct_validity")
    private BigDecimal constructValidity;

    // 异常回答分析
    @Column(name = "abnormal_responses")
    @Builder.Default
    private Long abnormalResponses = 0L;

    @Column(name = "suspicious_patterns")
    @Builder.Default
    private Long suspiciousPatterns = 0L;

    @Column(name = "common_errors")
    private String commonErrors; // JSON格式存储常见错误

    @Column(name = "misconception_identified")
    private Boolean misconceptionIdentified;

    @Column(name = "misconception_details", length = 1000)
    private String misconceptionDetails;

    // 群体差异分析
    @Column(name = "performance_by_group")
    private String performanceByGroup; // JSON格式存储不同群体表现

    @Column(name = "demographic_analysis")
    private String demographicAnalysis; // JSON格式存储人口统计分析

    @Column(name = "regional_differences")
    private String regionalDifferences; // JSON格式存储地域差异

    // 改进建议
    @Column(name = "improvement_suggested")
    private Boolean improvementSuggested;

    @Enumerated(EnumType.STRING)
    @Column(name = "improvement_priority", length = 20)
    private ImprovementPriority improvementPriority;

    @Column(name = "suggestion_type", length = 100)
    private String suggestionType;

    @Column(name = "suggestion_details", length = 1000)
    private String suggestionDetails;

    @Column(name = "revision_required")
    private Boolean revisionRequired;

    @Enumerated(EnumType.STRING)
    @Column(name = "revision_urgency", length = 20)
    private RevisionUrgency revisionUrgency;

    // 预测指标
    @Column(name = "predicted_performance")
    private BigDecimal predictedPerformance;

    @Column(name = "confidence_level")
    private BigDecimal confidenceLevel;

    @Column(name = "sample_size")
    @Builder.Default
    private Long sampleSize = 0L;

    @Column(name = "margin_of_error")
    private BigDecimal marginOfError;

    @Column(name = "statistical_significance")
    private Boolean statisticalSignificance;

    // 历史对比
    @Column(name = "historical_comparison")
    private String historicalComparison; // JSON格式存储历史对比数据

    @Column(name = "trend_analysis")
    private String trendAnalysis; // JSON格式存储趋势分析

    @Enumerated(EnumType.STRING)
    @Column(name = "performance_trend", length = 20)
    private PerformanceTrend performanceTrend;

    // 附加信息
    @Column(name = "analysis_method", length = 100)
    private String analysisMethod;

    @Enumerated(EnumType.STRING)
    @Column(name = "data_quality", length = 20)
    private DataQuality dataQuality;

    @Column(name = "notes", length = 1000)
    private String notes;

    @Column(name = "analyst", length = 50)
    private String analyst;

    @Column(name = "reviewed")
    @Builder.Default
    private Boolean reviewed = false;

    @Column(name = "reviewed_by", length = 50)
    private String reviewedBy;

    @Column(name = "review_date")
    private LocalDateTime reviewDate;

    @Column(name = "review_comments", length = 1000)
    private String reviewComments;

    @Column(name = "metadata", columnDefinition = "TEXT")
    private String metadata;

    // 标准审计字段
    @UpdateTimestamp
    @Column(name = "updated_time", nullable = false)
    private LocalDateTime updatedTime;

    @Version
    @Column(name = "version", nullable = false)
    @Builder.Default
    private Integer version = 0;

    @Column(name = "is_deleted", nullable = false)
    @Builder.Default
    private Boolean isDeleted = false;

    // 关联关系
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "question_id", insertable = false, updatable = false)
    private Question question;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "paper_id", insertable = false, updatable = false)
    private com.edu.exam.entity.exampaper.BasicExamPaper examPaper;

}